#include <iostream>
#include <vector>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

#define NUM 3

int *p = NULL;

//线程数据
struct threadData
{
    string threadname;
}; 


string toHex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}

void InitThreadData(threadData *td, int number)
{
    //thread-number
    td->threadname = "thread-" + to_string(number);
}

int g_val = 100;
//所有的线程都是执行这个函数 

void *threadRoutine(void *args)
{
    // int test_i = 0;
    //强转
    threadData *td = static_cast<threadData *>(args);
    // if(td->threadname == "thread-2") p = &test_i;
    int i = 0;
    while (i < 10)
    {
        cout << "pid: " << getpid() 
             << ", tid: " << toHex(pthread_self()) 
             << ", threadname: " << td->threadname 
             << ", g_val: "<< g_val 
             << ", &g_val: " << &g_val 
             << endl;
        
        sleep(1);
        i++, g_val++;
    }
    delete td;
    return nullptr;
}

int main()
{
    //创建多线程
    vector<pthread_t> tids;

    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        //创建一个结构体td对象
        //说明所有的线程共享堆空间
        threadData *td = new threadData;
        //初始化td对象的变量
        InitThreadData(td, i);
        //创建线程
        pthread_create(&tid, nullptr, threadRoutine,td);
        //
        tids.push_back(tid);
        sleep(1);

    }

    sleep(1);//确保复制成功
    // cout << "main thread get a thread local value, val:" << *p <<", &val: " << p << endl;

    for (int i = 0; i < tids.size(); i++)
    { 
        //等待线程退出
        pthread_join(tids[i], nullptr);
    }
    return 0;
}
